<!-- 基础类型管理 -->
<template>
  <div style="height: 100%">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :key="index" v-for="(item, index) in breadcrumbItems">{{ item }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="table-wrap-box">
      <el-container style="height: 100%">
        <el-aside class="side-wrap" width="220">
          <SideCategoryMenu :categoriesTree="categoriesTree" @add-btn-click="addBtnClick" @del-btn-click="delBtnClick"
            @edit-btn-click="editBtnClick" @tree-node-click="treeNodeClick"
            @tree-node-cancel-check="treeNodeCancelCheckHandler" />
        </el-aside>
        <el-main class="main-wrap">
          <div style="width: 160px;display: flex;justify-content: space-around;margin-bottom: 4px">
            <el-button size="mini" icon="el-icon-plus" type="primary" @click="addTypeClick">新增</el-button>
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="delTypeClick">删除</el-button>
          </div>
          <el-table :data="basicTypeData" :max-height="1000" border fit row-key="id" size="mini" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40">
            </el-table-column>
            <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
              align="center">
              <template slot-scope="scope">
                <span v-if="item.oper">
                  <el-button size="mini" type="text" @click="rowEditTypeClick(scope.row)">编辑</el-button>
                  <el-button size="mini" type="text" style="color: #f56c6c" @click="rowDelTypeClick">删除</el-button>
                </span>
                <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-card>

  </div>
</template>
<script>

import CategoryForm from "@/components/feature/CategoryForm";
import { $FeatureApi } from "@/network/feature/FeatureApi";
import { $BasicTypeApi } from "@/network/feature/BasicTypeApi";
import BasicTypeForm from "@/components/feature/BasicTypeForm";
import SideCategoryMenu from "@/components/feature/SideCategoryMenu";
import { useDialog } from "@/components/dialog/BaseDialog";
import { useFormDialog } from "@/components/formDialog/FormDialog";

import '@/assets/css/featureLayout.css';
import BaseDialog from "@/components/dialog/BaseDialog.vue";

export default {
  name: "BasicTypeManage",
  components: {
    SideCategoryMenu,
    BasicTypeForm,
    CategoryForm,
  },
  data() {
    return {
      breadcrumbItems: [],
      categoriesTree: [],
      curKind: '',      // 当前特征种类
      selectNode: null,   // 当前选择的节点
      columns: [
        { prop: 'name', label: '名称', width: "150", oper: false },
        { prop: 'text', label: '显示名称', width: "180", oper: false },
        { prop: 'categoryName', label: '分类', width: "150", oper: false },
        { prop: 'jdbcTypeLabel', label: '存储类型', width: "150", oper: false },
        { prop: 'description', label: '描述', width: "200", oper: false },
        { prop: '', label: "操作", width: "230", oper: true }
      ],
      basicTypeData: [],
      treeOper: '',   // 分类树操作类别 add, edit
      tableOper: '',  // 基础类型表格操作类别 add, edit
      checkedIds: [],  // 表格选中行
      // jdbcTypeArray: [],  // 存储类型 varchar, int, double等
      categoryForm: {
        id: '',
        name: '',
        parentId: '',
        parentLabel: '',
      },
      basicTypeForm: {
        categoryId: '',
        categoryName: '',
        name: '',
        text: '',
        jdbcTypeName: "",
        description: '',
        jdbcTypeArray: [],
      },
    }
  },

  methods: {
    // 添加分类
    addBtnClick() {
      useFormDialog({
        title: "添加分类",
        width: "800px",
        formProps: {
          kind: this.curKind,
          parentLabel: this.selectNode ? this.selectNode.label : "",
          parentId: this.selectNode ? this.selectNode.id : ""
        }
      }, CategoryForm, async (data) => {
        const res = await $FeatureApi.saveCategory(data);
        this.ShowMessage(res);
        this.loadCategoryTree();
      }, null);

    },

    async loadCategoryTree() {
      let res = await $FeatureApi.getCategoryTreeData({ kind: this.curKind });
      this.categoriesTree = [...res.data];
    },

    // 点击树节点
    treeNodeClick(node) {
      let { id, name, label, parentId, parentLabel } = { ...node };
      this.selectNode = { id, name, label, parentId, parentLabel };
      this.loadBasicTypeData();
    },

    // 分类树节点取消选中
    treeNodeCancelCheckHandler() {
      this.selectNode = null;
      Object.keys(this.categoryForm).forEach(key => {
        this.categoryForm[key] = "";
      })
    },
    // 删除按钮点击
    delBtnClick() {
      if (!this.selectNode) {
        this.$message.info("请选择要删除的类型");
      } else {
        let msg = '确定删除选择的类型: ' + '"' + this.selectNode.label + '"';
        this.$confirm(msg, "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await $FeatureApi.deleteCategory({ id: this.selectNode.id, kind: 'basic' });
          if (this.$ResHandler.isOk(res)) {
            this.$message.success(res.msg);
            await this.loadCategoryTree();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          this.$message.info("取消操作");
        })
      }
    },
    // 弹窗关闭
    handleCloseClick() {
      this.treeNodeCancelCheckHandler();
    },

    // 渲染节点内容
    renderNodeContent(h, { node, data, store }) {
      let iconClass = 'el-icon-document'
      if (node.childNodes && node.childNodes.length > 0) {
        if (node.expanded) {
          iconClass = 'el-icon-folder-opened';
        } else {
          iconClass = 'el-icon-folder';
        }
      }
      return h('span', [
        h('i', { class: iconClass }),
        h('span', " "),
        h('span', { class: 'tree-node-text' }, data.label)
      ])
    },

    // 编辑分类
    editBtnClick() {
      if (!this.selectNode) {
        this.$message.error("请选择一项分类进行编辑");
        return;
      }
      this.categoryForm = { ...this.selectNode };
      useFormDialog({
        title: "编辑分类",
        width: "800px",
        formProps: {
          kind: this.curKind,
          name: this.selectNode.name,
          parentLabel: this.selectNode.parentLabel,
          parentId: this.selectNode.parentId
        }
      }, CategoryForm, async (data) => {
        data.id = this.selectNode.id;
        let res = await $FeatureApi.updateCategory(data);
        this.ShowMessage(res);
        this.loadCategoryTree();
      }, null);
    },

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 加载基础类型表格数据
    async loadBasicTypeData() {
      let categoryId = "";
      if (this.selectNode) {
        categoryId = this.selectNode.id;
      }
      let params = {
        categoryId,
      }
      let res = await $BasicTypeApi.getBasicTypeTableData(params);
      if (this.$ResHandler.isOk(res)) {
        this.basicTypeData = res.data;
      }
    },
    // 新增基础类型
    addTypeClick() {
      if (!this.selectNode) {
        this.$message.error("请选择一项类型分类!");
        return;
      }
        
      useFormDialog({
        title: "新增基础类型",
        formProps: {
          categoryId: this.selectNode.id,
          categoryName: this.selectNode.name,
          jdbcTypeArray: this.basicTypeForm.jdbcTypeArray
        }
      }, BasicTypeForm, async (data) => {
        let res = await $BasicTypeApi.createBasicType({ ...data })
        this.ShowMessage(res);
        this.loadBasicTypeData();
      }, () => { });
    },

    // 基础类型表格新增,编辑弹框确定
    async handleBTOkClick() {
      const { jdbcTypeArray, ...data } = this.basicTypeForm;
      let res = null;
      if (this.tableOper === "add") {
        res = await $BasicTypeApi.createBasicType(data);
      } else {
        res = await $BasicTypeApi.updateBasicType(data);
      }
      if (res && this.$ResHandler.isOk(res)) {
        this.$message.success(res.msg);
        await this.loadBasicTypeData();
      } else {
        this.$message.error(res.msg);
      }
    },

    handleBTCloseClick() {
      this.$refs.btForm.clearFormData();
    },

    // 表格选中项改变
    handleSelectionChange(val) {
      this.checkedIds = val.map(item => {
        return item.id;
      })
    },

    // 删除基础类型
    delTypeClick() {
      let ids = [...this.checkedIds];
      if (!ids || ids.length === 0) {
        this.$message.error("请选择要删除的类型");
        return;
      }
      this.$confirm('将删除选择的类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await $BasicTypeApi.deleteBasicTypeByIds({
          ids
        });
        if (this.$ResHandler.isOk(res)) {
          this.$message.success(res.msg);
          await this.loadBasicTypeData();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(err => {
        this.$message.success("取消操作");
      })
    },

    //
    rowEditTypeClick(row) {
      let jdbcTypeArray = this.basicTypeForm.jdbcTypeArray;
      this.basicTypeForm = { ...row };
      this.basicTypeForm.jdbcTypeArray = jdbcTypeArray;
      console.log(this.basicTypeForm);
      useDialog(BasicTypeForm, {
        title: "添加基础类型",
        formData: this.basicTypeForm,
      }, this.handleBTOkClick, this.handleBTCloseClick);
    },

    // 表格行点删除
    rowDelTypeClick() {

    },

    //
    async loadAllJdbcType() {
      const res = await $BasicTypeApi.listAllJdbcType();
      this.basicTypeForm.jdbcTypeArray = res.data;
    }

  },

  watch: {
    $route: {
      handler: function (newRoute, oldRoute) {
        this.breadcrumbItems = ['特征中心', newRoute.meta.description];
        this.curKind = newRoute.meta.name;
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.loadCategoryTree();
    this.loadBasicTypeData();
    this.loadAllJdbcType();
  }
}
</script>

<style scoped>
::v-deep .tree-node-text {
  font-size: 14px;
}
</style>